package cn.seven._conf._handler;

/**
 * create by 张天笑, 2017/8/29 1:47
 */

import com.jfinal.kit.PropKit;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/*
* 全局拦截异常
* 1.打印日志
* 2.转发给ErrorController,spring知道该返回json还是html
* */
@ControllerAdvice
public class GlobalDefaultExceptionHandler {
    private final Logger logger = Logger.getLogger(GlobalDefaultExceptionHandler.class);
    public final String ctx = PropKit.get("ctx");

    @ExceptionHandler(value = Throwable.class)
    public void defaultErrorHandler(HttpServletRequest request, HttpServletResponse response,
                                    Exception e) {
        //System.out.println(request.getHeader("Accept"));//text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
         /*
        * 打印日志
        * */

        logger.info("出错请求:  " + request.getMethod() + "  " + request.getRequestURI());
        try {
            /*
            *  记录异常， 转发到异常接口
            * */
            if (e instanceof org.springframework.web.servlet.NoHandlerFoundException ||
                    e instanceof org.springframework.web.HttpRequestMethodNotSupportedException) {
                //response.sendRedirect(ctx + "error/404");
                request.getRequestDispatcher("/error/404").forward(request, response);
            } else if (e instanceof org.springframework.web.multipart.MultipartException) {
                //文件上传异常, file size超出|上传下载异常终止
                logger.error("-----Global-------500------    " + new Date().toLocaleString(), e);
                response.setStatus(500);
                request.getRequestDispatcher("/error/500").forward(request, response);
                /*Sky sky = new Sky(0, "上传失败");
                WebTool.renderJson(response, sky);*/
            } else {
                logger.error("-----Global-------500------    " + new Date().toLocaleString(), e);
                //response.sendRedirect(ctx + "error/500");
                //设置状态码为200
                response.setStatus(500);
                //转发到ErrorController, code:0, msg: e.getMsg();
                //request.setAttribute("sky", new Sky<Object>(0, e.getMessage()));
                request.getRequestDispatcher("/error/500").forward(request, response);
            }
        } catch (Exception e1) {
            logger.error(" ######## ", e1);
        }
    }


}